import asyncio

from app.utils.kafka import KafkaConsumer
from app.utils.logger import logger
import aiohttp


async def send_message(group_id, message, contain_type):
    try:
        async with aiohttp.ClientSession() as session:
            payload = await make_payload(group_id, contain_type, message)
            async with session.post("http://localhost:3000/send", json=payload) as response:
                if response.status == 200:
                    logger.info(f"Message sent successfully to group {group_id}")
                else:
                    logger.error(f"Failed to send message to group {group_id}. Status: {response.status}")
    except Exception as e:
        logger.error(f"Error sending message: {e}")


async def make_payload(group_id, contain_type, contain):
    # 构建消息的基础结构
    message = []

    # 如果是图片类型，构建图片消息结构
    if contain_type == 'image':
        message.append({
            'type': contain_type,
            'data': {
                'file': contain  # 这里使用 'file' 来传递图片路径
            }
        })

    # 对于文本消息
    elif contain_type == 'text':
        message.append({
            'type': contain_type,
            'data': {
                'text': contain  # 这里使用 'text' 来传递文本内容
            }
        })

    # 构建最终的 payload 结构
    payload = {
        'group_id': group_id,
        'message': message  # 包含消息段的列表
    }

    return payload


class MessageSender:
    def __init__(self):
        self.kafka_consumer = KafkaConsumer("qq_send_messages")

    async def start(self):
        logger.info("MessageSender started and waiting for messages...")
        async for msg in self.kafka_consumer.consume():
            logger.info(f"Received message from qq_send_messages topic: {msg}")
            asyncio.create_task(send_message(msg["group_id"], msg["message"], msg["contain_type"]))

